package com.ocom.company.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.dto.GetCompanyRoleListDto;
import com.ocom.common.entity.human.EntityResourceApi;
import com.ocom.common.entity.human.EntityResourceMenu;
import com.ocom.common.entity.master.EntityCompanyRole;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.companyrole.GetRoleUserRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.company.CompanyRoleListVo;
import com.ocom.company.service.CompanyRoleService;
import com.ocom.company.service.ResourceApiService;
import com.ocom.company.service.ResourceMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class CompanyRoleController {

    @Autowired
    private CompanyRoleService companyRoleService;

    @Autowired
    private ResourceApiService resourceApiService;

    @Autowired
    private ResourceMenuService resourceMenuService;


    @PostMapping(CompanyServiceUrl.URL_getCompanyRole)
    public Result getCompanyRole(@RequestBody GetCompanyRoleListDto dto) {
        List<CompanyRoleListVo> list = companyRoleService.getCompanyRole(dto.getComId(), dto.getRoleId());
        return ResultUtil.success(list);
    }


    @PostMapping(CompanyServiceUrl.URL_addCompanyRole)
    public Result addCompanyRole(@RequestParam("companyId") Long companyId, @RequestBody EntityCompanyRole entityCompanyRole) {
        int count = companyRoleService.countCompanyRole(companyId, entityCompanyRole.getRoleId(), entityCompanyRole.getRoleName(), 1);
        if (0 < count) {
            return ResultUtil.error(ResultEnum.Err_4080);
        }
        count = companyRoleService.countCompanyRole(companyId, entityCompanyRole.getRoleId(), entityCompanyRole.getRoleName(), 2);
        if (0 < count) {
            return ResultUtil.error(ResultEnum.Err_4081);
        }
        boolean result = companyRoleService.addCompanyRole(companyId, entityCompanyRole);
        return result ? ResultUtil.success(entityCompanyRole) : ResultUtil.error(ResultEnum.Err_2016);
    }

    @PostMapping(CompanyServiceUrl.URL_modifyCompanyRole)
    public Result modifyCompanyRole(@RequestParam("companyId") Long companyId, @RequestParam("roleId") Long roleId, @RequestParam("roleName") String roleName) {
        int count = companyRoleService.countCompanyRole(companyId, roleId, roleName, 1);
        if (0 < count) {
            return ResultUtil.error(ResultEnum.Err_4080);
        }
        count = companyRoleService.countCompanyRole(companyId, roleId, roleName, 3);
        if (0 < count) {
            return ResultUtil.error(ResultEnum.Err_4081);
        }
        boolean result = companyRoleService.modifyCompanyRole(companyId, roleId, roleName);
        return result ? ResultUtil.success() : ResultUtil.error(ResultEnum.Err_3014);
    }

    @PostMapping(CompanyServiceUrl.URL_delCompanyRole)
    public Result delCompanyRole(@RequestParam("companyId") Long companyId, @RequestParam("roleId") Long roleId) {
        companyRoleService.delCompanyRole(companyId, roleId);
        return ResultUtil.success();
    }


    /**
     * 4.28获取角色用户小程序菜单权限（getAppMenuByRole）
     */
    @PostMapping(CompanyServiceUrl.URL_getAppMenuByRole)
    public Result getAppMenuByRole(@RequestBody GetRoleUserRequest request) {

        Map<String, Object> map = new HashMap<>();
        List<EntityResourceApi> pageList = resourceApiService.getPageList(request.getRole());
        List<EntityResourceApi> buttoneList = resourceApiService.getButtoneList(request.getRole());
        List<EntityResourceMenu> menuList = resourceMenuService.getMenuList(request.getSaasNo(), request.getRole());
        if (menuList == null || menuList.size() <= 0) {
            List<EntityResourceMenu> list = new ArrayList<>();
            map.put("menuTree", list);
            return ResultUtil.success(map);
        }

        if (menuList.get(0).getType() != 0) {
            List<EntityResourceMenu> list = new ArrayList<>();
            map.put("menuTree", list);
            return ResultUtil.success(list);
        }
//        List<EntityResourceMenu> list = new ArrayList<>();
//
//        Map<Integer, String> pageIds = pageList.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getApiAppCode(), (e1, e2) -> e1));
//
//        for (EntityResourceMenu menuNode : menuList) {
//            //
//            System.out.println(menuNode);
//            if (pageIds.containsKey(menuNode.getPageId())) {
//                if (menuNode.getXfVerList() != null || menuNode.getMjVerList() != null) {
//                    String[] strMjVer = menuNode.getMjVerList() != null ? menuNode.getMjVerList().split(",") : new String[0];//根据，切分字符串
//                    String[] strXfVer = menuNode.getXfVerList() != null ? menuNode.getXfVerList().split(",") : new String[0];//根据，切分字符串
//
//                    List<String> mjList = Arrays.asList(strMjVer);
//                    List<String> xfList = Arrays.asList(strXfVer);
//                    if (xfList.contains(request.getXfVer().toString()) || mjList.contains(request.getMjVer().toString())) {
//                        menuNode.setPageCode(pageIds.get(menuNode.getPageId()));
//                        list.add(menuNode);
//                    }
//                }
//            }
//        }
//
//        map.put("menuTree", list);
        if (menuList == null || menuList.size()<=0){
            List<EntityResourceMenu> list=new ArrayList<>();
            map.put("menuTree",list);
            return ResultUtil.success(map);
        }
        EntityResourceMenu entityResourceMenuOne=null;
        if (menuList.get(0).getType()!=0){
            List<EntityResourceMenu> list=new ArrayList<>();
            map.put("menuTree",list);
            return ResultUtil.success(list);
        }
        List<EntityResourceMenu> list=builTree(menuList,pageList,buttoneList, JSON.parseObject(JSON.toJSONString(request)));
        if (entityResourceMenuOne !=null){
            list.add(entityResourceMenuOne);
        }

        removeBuilTree(list);

        map.put("menuTree",list);
        return ResultUtil.success(map);
    }
    public List<EntityResourceMenu> removeBuilTree(List<EntityResourceMenu> menuList) {
        for (EntityResourceMenu menuNode : getRootNode( menuList)) {
            removeTree(menuNode);
        }
        return menuList;
    }

    private EntityResourceMenu removeTree(EntityResourceMenu FuEntityResourceMenu){
        List<EntityResourceMenu> list=FuEntityResourceMenu.getChildMenu();
        List<EntityResourceMenu> treeMenus = new ArrayList<EntityResourceMenu>();
        for (EntityResourceMenu entityResourceMenu : list) {
            if (entityResourceMenu.getType()==1 || entityResourceMenu.getType() == 99 || entityResourceMenu.getType() == 100){
                if (entityResourceMenu.getChildMenu() !=null && entityResourceMenu.getChildMenu().size()>0){
                    treeMenus.add(entityResourceMenu);
                }
                if(ObjectUtil.isEmpty(entityResourceMenu.getChildMenu())){
                    removeTree(entityResourceMenu);
                }
            }else {
                treeMenus.add(entityResourceMenu);
            }
            if (entityResourceMenu.getChildMenu() !=null && entityResourceMenu.getChildMenu().size()>0){
                removeTree(entityResourceMenu);
            }
        }
        FuEntityResourceMenu.setChildMenu(treeMenus);
        return FuEntityResourceMenu;
    }
    //建立树形结构
    public List<EntityResourceMenu> builTree(List<EntityResourceMenu> menuList, List<EntityResourceApi> pageList, List<EntityResourceApi> buttoneList, JSONObject jsonObject) {
        List<EntityResourceMenu> treeMenus = new ArrayList<EntityResourceMenu>();
        List<EntityResourceMenu> rootMenu = getRootNode( menuList);
        for (EntityResourceMenu menuNode : rootMenu) {
            menuNode.setMenuId(menuNode.getId());
            menuNode = buildChilTree(menuNode,menuList,pageList,buttoneList,jsonObject);
            menuNode.setXfVerList(null);
            menuNode.setMjVerList(null);
            // menuNode.setDescription(null);
            menuNode.setUpdateTime(null);
            menuNode.setCreateTime(null);
            menuNode.setId(null);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }
    //递归，建立子树形结构
    private EntityResourceMenu buildChilTree(EntityResourceMenu resourceMenu,List<EntityResourceMenu> menuList,List<EntityResourceApi> pageList,List<EntityResourceApi> buttoneList,JSONObject jsonObject) {
        //子集合
        List<EntityResourceMenu> chilMenus = new ArrayList<EntityResourceMenu>();
        //
        Set<Integer> menuIds = new HashSet<>();
        for (EntityResourceMenu menuNode : menuList) {
            //
            if (menuNode.getParentId().equals(resourceMenu.getMenuId())) {
                //子级
                if (menuNode.getType()==2 || menuNode.getType()==3 || menuNode.getType()==101){
                    if (menuNode.getXfVerList()!=null){
                        String[] strXfVer = menuNode.getXfVerList().split(",");//根据，切分字符串
                        for (String s : strXfVer) {
                            if (s.equals(jsonObject.getString("xfVer"))){
                                if (menuNode.getType()==2 || menuNode.getType()==101){
                                    for (EntityResourceApi entityResourceApi : pageList) {

                                        if (menuNode.getPageId().compareTo(entityResourceApi.getId())==0){
                                            menuNode.setPageCode(entityResourceApi.getApiAppCode());
                                            menuNode.setPermission(entityResourceApi.getPermission());
                                            if (menuNode.getName() ==null){
                                                menuNode.setName(entityResourceApi.getApiName());
                                            }
                                            if (entityResourceApi.getPermission()==2){
                                                for (EntityResourceApi resourceApi : buttoneList) {
                                                    if (resourceApi.getPageId().compareTo(entityResourceApi.getId())==0){
                                                        menuNode.setPageButton(resourceApi.getApiCode());
                                                    }
                                                }
                                            }
                                            menuNode.setMenuId(menuNode.getId());
                                            if(!menuIds.contains(menuNode.getId())){
                                                chilMenus.add(buildChilTree(menuNode,menuList,pageList,buttoneList,jsonObject));
                                            }
                                            menuIds.add(menuNode.getId());
                                        }
                                    }
                                }else {
                                    menuNode.setMenuId(menuNode.getId());
                                    if(!menuIds.contains(menuNode.getId())) {
                                        chilMenus.add(buildChilTree(menuNode, menuList, pageList, buttoneList, jsonObject));
                                    }
                                    menuIds.add(menuNode.getId());
                                }
                            }
                        }
                    }

                    if (menuNode.getMjVerList() !=null){
                        String[] strMjVer = menuNode.getMjVerList().split(",");//根据，切分字符串
                        for (String s : strMjVer) {
                            if (s.equals(jsonObject.getString("mjVer"))){
                                if (menuNode.getType()==2 || menuNode.getType()==3 || menuNode.getType()==101){
                                    for (EntityResourceApi entityResourceApi : pageList) {
                                        if (menuNode.getPageId().compareTo(entityResourceApi.getId())==0){
                                            menuNode.setPageCode(entityResourceApi.getApiAppCode());
                                            menuNode.setPermission(entityResourceApi.getPermission());
                                            if (menuNode.getName() ==null){
                                                menuNode.setName(entityResourceApi.getApiName());
                                            }
                                            if (entityResourceApi.getPermission()==2){
                                                for (EntityResourceApi resourceApi : buttoneList) {
                                                    if (resourceApi.getPageId().compareTo(entityResourceApi.getId())==0){
                                                        menuNode.setPageButton(resourceApi.getApiCode());
                                                    }
                                                }
                                            }
                                            menuNode.setMenuId(menuNode.getId());
                                            chilMenus.add(buildChilTree(menuNode,menuList,pageList,buttoneList,jsonObject));
                                        }
                                    }
                                }else {
                                    menuNode.setMenuId(menuNode.getId());
                                    chilMenus.add(buildChilTree(menuNode,menuList,pageList,buttoneList,jsonObject));
                                }
                            }
                        }
                    }
                }else {
                    menuNode.setMenuId(menuNode.getId());
                    chilMenus.add(buildChilTree(menuNode,menuList,pageList,buttoneList,jsonObject));
                }
            }
        }

        resourceMenu.setChildMenu(chilMenus);
        resourceMenu.setId(null);
        resourceMenu.setXfVerList(null);
        resourceMenu.setMjVerList(null);
        // resourceMenu.setDescription(null);
        resourceMenu.setUpdateTime(null);
        resourceMenu.setCreateTime(null);
        return resourceMenu;
    }
    //获取根节点
    private List<EntityResourceMenu> getRootNode(List<EntityResourceMenu> menuList) {
        List<EntityResourceMenu> rootMenuLists = new ArrayList<EntityResourceMenu>();
        for (EntityResourceMenu menuNode : menuList) {
            if (menuNode.getParentId()==0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

}
